# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import webapp2
from wowgae.model import ShortURL
from wowgae.web import WebHandler


class CustomizeShortURLHandler(WebHandler):
    """Helps administrators registering custom short URLs."""

    def __general_data(self):
        config = self.app.config.get('wowgae.short')
        data = {'domain': config['domain']}
        return data

    def get(self):
        self.template.use('admin', 'shortener', 'custom')
        data = self.__general_data()
        self.template.update(admin={'shortener': data})
        self.template.write()

    def post(self):
        self.template.use('admin', 'shortener', 'custom')
        data = self.__general_data()
        code = self.request.get('code')
        url = self.request.get('url')
        if len(code) < 4 or len(code) > 50:
            data['error'] = u'O código não pode ser menor que 4 caracteres' + \
                             ' ou maior que 50. Tente alterar seu tamanho.'
        else:
            fancy = ShortURL.store_custom_url('admin',
                                              self.current_user.user_id(),
                                              url, code)
            data['result'] = 'http://%s/%s' % (data['domain'], fancy)
            data['path'] = fancy
            data['original'] = url
        self.template.update(admin={'shortener': data})
        self.template.write()


class CreateShortURLHandler(WebHandler):
    """Enables creating short URLs."""

    def __general_data(self):
        config = self.app.config.get('wowgae.short')
        data = {'domain': config['domain']}
        return data

    def get(self):
        """Returns a short URL form or shortened URL."""
        url = self.request.get('url')
        data = self.__general_data()
        self.template.use('short', 'create')
        if url:
            if self.current_user:
                user_id = self.current_user.user_id()
            else:
                user_id = ''
            url = self.request.get('url')
            fancy = ShortURL.store_url('share', user_id, url)
            data['result'] = 'http://%s/%s' % (data['domain'], fancy)
            data['path'] = fancy
            data['original'] = url
        self.template.update(short=data)
        self.template.write()


class ShortURLHandler(webapp2.RequestHandler):
    """Handles redirecting to the given resource."""

    def get(self, code):
        """Redirects to the given code."""
        code = code.decode('utf-8')
        home = webapp2.uri_for('home', self.request)
        url = ShortURL.click_code(code) or home
        self.redirect(url)
